package com.sfang.common.base.http.Interceptor;

import org.springframework.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author lilei
 * @date 2021/08/31
 * 修改处理方式，去掉final修饰；
 * 代码恢复，不影响
 * ===============================
 * 包装request可以重复读取body内容
 *
 * @author xuzilou
 * @date 2021/3/24 17:21
 */
public class BodyReaderRequestWrapper extends HttpServletRequestWrapper {
    private final byte[] body;
    private HttpServletRequest req;

    public BodyReaderRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        body = StreamUtils.copyToByteArray(request.getInputStream());
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream byteArrayIns = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }

            @Override
            public int read() {
                return byteArrayIns.read();
            }
        };
    }
}
